<!-- 运费配置 -->
<template>
  <div class="content">
    <div class="content-container">
      <div class="content-btn">
        <Cbutton @click="handleAdd">新建运费模板</Cbutton>
      </div>
      <!-- <Regions @getData="getRegionsData"></Regions> -->
      <el-table :data="tableList" v-loading="tableLoading" ref="tableData" border fit>
        <el-table-column label="序号" type="index" align="center" width="70"></el-table-column>
        <el-table-column prop="name" label="模板名称" align="center"></el-table-column>
        <el-table-column prop="chargeType" label="计费方式" align="center">
          <template slot-scope="scope">
            {{ dealListStr(scope.row.chargeType, 'chargeStyleList') }}
          </template>
        </el-table-column>
        <el-table-column prop="regionCount" label="条数" align="center"></el-table-column>
        <!-- <el-table-column prop="dest" label="目的地" align="center"></el-table-column> -->
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            {{scope.row.createTime | glbTimeFormat}}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center">
          <template slot-scope="scope">
            {{scope.row.updateTime | glbTimeFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <span class="click-ele" @click="handleEdit(scope.row, 2)">编辑</span>
            <span class="click-ele danger" @click="handleRemove(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <el-dialog :title="modelDialog.title" :visible.sync="modelDialog.show" v-if="modelDialog.show" width="1000px">
      <el-form :model="modelDialog.data" :rules="modelDialog.rules" ref="DlalogForm" size="medium" label-width="100px"
               class="freight-model-form">
        <el-form-item label="模板名称：" prop="name">
          <el-input v-model="modelDialog.data.name" placeholder="请输入模板名称" :disabled="modelDialog.type === 'EDIT'" style="width: 300px;"></el-input>
        </el-form-item>
        <el-form-item label="计费方式：" prop="chargeType">
          <el-radio-group v-model="modelDialog.data.chargeType" :disabled="modelDialog.type === 'EDIT'">
            <el-radio :label="item.value" v-for="item in chargeStyleList" :key="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="0px">
          <Cbutton @click="handleAddRegion" size="small">添加区域</Cbutton>
        </el-form-item>
        <el-form-item label-width="0px">
          <!-- 区域 -->
          <el-table :data="modelDialog.tableList" v-loading="modelDialog.tableLoading" ref="tableData" border fit
                    :row-class-name="handleSetRowClassName">
            <el-table-column label="序号" type="index" align="center" width="70"></el-table-column>
            <el-table-column prop="regionName" label="可配送区域" align="center" width="300">
              <template slot-scope="scope">
                <span>{{scope.row.parentRegionName ? scope.row.parentRegionName + '-' : ''}}</span>
                <span>{{scope.row.regionName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="firstWeight" :label="modelDialog.data.chargeType === '1' ? '首件（个）' : '首重（kg）'" align="center">
              <template slot-scope="scope">
                <el-input class="text-center" v-model="scope.row.firstWeight"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="firstFee" label="运费（元）" align="center">
              <template slot-scope="scope">
                <el-input class="text-center" v-model="scope.row.firstFee"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="continueWeight" :label="modelDialog.data.chargeType === '1' ? '续件（个）' : '续重（kg）'"
                             align="center">
              <template slot-scope="scope">
                <el-input class="text-center" v-model="scope.row.continueWeight"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="continueFee" label="续费（元）" align="center">
              <template slot-scope="scope">
                <el-input class="text-center" v-model="scope.row.continueFee"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="操作" align="center">
              <template slot-scope="scope">
                <span class="click-ele" @click="handleRegionsEdit(scope.row, scope.$index)">编辑</span>
                <span class="click-ele danger" @click="handleRegionsRemove(scope.$index, scope.row)">删除</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label-width="0px">
          <span style="color:#E6A23C;">请检查数据是否准确、完整！！！</span> <br />
          <Cbutton :btnloading="modelDialog.btnLoading" size="medium" @click="handleSubmit('DlalogForm')">保存</Cbutton>
          <Cbutton type="" size="medium" @click="handleCancle">取消</Cbutton>
        </el-form-item>

      </el-form>

      <el-dialog :title="regionsDialog.title" v-if="regionsDialog.show" :visible.sync="regionsDialog.show" width="700px"
                 append-to-body :show-close="false">
        <Regions @getData="getRegionsData" :limit="regionsDialog.limit"></Regions>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { ExportList, ExportStr } from '@/utils'
import { GetFreightModelList, AddFreightModel, UpdateFreightModel, DeleteFreightModel, GetFreightModelDetail } from '@/api/onlineMan'
import Regions from '@/components/Regions/regions'
export default {
  name: 'freightModel',
  components: { Regions },
  data () {
    return {
      query: {
        pageNum: 1,
        pageSize: 10
      },
      totalCount: 0,
      tableList: [],
      tableLoading: false,
      modelDialog: {
        show: false,
        title: '',
        type: '',
        data: {
          id: '',
          name: '',
          chargeType: ''
        },
        regionList: [],
        tableList: [],
        tableLoading: false,
        btnLoading: false,
        rules: {}
      },
      regionsDialog: {
        show: false,
        limit: NaN,
        index: NaN, // 保存点击编辑地区的一行下标
        title: '选择配送区域'
      },
      chargeStyleList: ExportList('chargeStyleList')
    }
  },
  props: {},
  watch: {},
  computed: {},
  mounted () {
    this.getList()
  },
  methods: {
    getList () {
      this.tableLoading = true
      let params = JSON.parse(JSON.stringify(this.query))
      GetFreightModelList(params).then(res => {
        this.tableLoading = false
        const data = res.data
        this.tableList = data.list
      }).catch(e => {
        this.tableLoading = false
      })
    },
    handleRemove (row) {
      this.$confirm(`确定要删除该模板吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = { id: row.id }
        DeleteFreightModel(params).then(res => {
          this.getList()
        }).catch(e => { })
      }).catch(e => { })
    },
    handleAdd () {
      this.modelDialog.title = '新建运费模板'
      this.modelDialog.type = 'ADD'
      this.modelDialog.data.id = ''
      this.modelDialog.data.name = ''
      this.modelDialog.data.chargeType = '0'
      this.modelDialog.show = true
      this.modelDialog.tableList = []
      this.modelDialog.regionList = []
    },
    handleEdit (row) {
      this.modelDialog.title = '修改运费模板'
      this.modelDialog.type = 'EDIT'
      this.handleGetDetail(row.id)
    },
    handleGetDetail (id) {
      this.modelDialog.tableList = []
      this.modelDialog.regionList = []
      this.modelDialog.tableLoading = true
      GetFreightModelDetail(id).then(res => {
        this.modelDialog.tableLoading = false
        try {
          const data = res.data
          for (const key in this.modelDialog.data) {
            if (key === 'chargeType') {
              this.modelDialog.data[key] = data[key].toString()
            } else {
              this.modelDialog.data[key] = data[key]
            }
          }

          data.regions.forEach(item => {
            this.modelDialog.tableList.push(item)
            this.modelDialog.regionList.push(item)
          })
          this.modelDialog.show = true
        } catch (error) {
          this.$message.error('数据错误')
        }
      }).catch(e => {
        this.modelDialog.tableLoading = false
      })
    },

    handleSubmit (formName, type) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false
        let params = {
          id: this.modelDialog.data.id || '',
          name: this.modelDialog.data.name,
          chargeType: this.modelDialog.data.chargeType,
          regionParams: []
        }
        params.regionParams = this.modelDialog.tableList || []
        if (!params.name) {
          this.$message.warning('请填写模板名称！')
          return
        }
        if (!params.chargeType) {
          this.$message.warning('请选择计费方式！')
          return
        }
        if (!this.modelDialog.tableList || this.modelDialog.tableList.length <= 0) {
          this.$message.warning('请选择配送区域！')
        } else {
          if (this.modelDialog.type === 'ADD') {
            delete params.id
            AddFreightModel(params).then(res => {
              this.modelDialog.show = false
              this.getList()
            }).catch(e => { })
          }
          if (this.modelDialog.type === 'EDIT') {
            let editParams = {
              id: params.id,
              regions: params.regionParams
            }

            UpdateFreightModel(editParams).then(res => {
              this.modelDialog.show = false
              this.getList()
            }).catch(e => { })
          }
        }
      })
    },

    handleCancle () {
      this.modelDialog.show = false
    },

    handleAddRegion () {
      this.regionsDialog.show = true
      this.regionsDialog.limit = NaN
    },
    handleRegionsEdit (row, $index) {
      this.regionsDialog.show = true
      this.regionsDialog.limit = 1
      this.regionsDialog.index = $index
    },
    handleRegionsRemove (index, row) {
      this.$confirm(`确定要删除该区域吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.bDelete = 1
        this.$set(this.modelDialog.tableList, index, row)
      }).catch(e => { })
    },

    getRegionsData (data) {
      this.regionsDialog.show = false
      if (data.limit === 1) {
        let parentRegionName = ''
        let info = {
          continueFee: '',
          continueWeight: '',
          firstFee: '',
          firstWeight: '',
          regionKey: '',
          regionName: '',
          parentRegionName: '',
          bDelete: 0
        }
        data.list.forEach(item => {
          info.regionKey = item.code
          info.regionName = item.name
          if (item.code2) {
            info.code2 = item.code2
            info.regionName2 = item.name2
            parentRegionName = item.name2
          }
          if (item.code3) {
            info.code3 = item.code3
            info.regionName3 = item.name3
            parentRegionName = item.name3 + '-' + parentRegionName
          }
          if (item.code4) {
            info.code4 = item.code4
            info.regionName4 = item.name4
            parentRegionName = item.name4 + '-' + parentRegionName
          }
          info.parentRegionName = parentRegionName
        })
        this.modelDialog.tableList[this.regionsDialog.index].regionKey = info.regionKey
        this.modelDialog.tableList[this.regionsDialog.index].regionName = info.regionName
        this.modelDialog.tableList[this.regionsDialog.index].parentRegionName = info.parentRegionName
      } else {
        const codeArr = this.modelDialog.tableList.map(item => item.regionKey)
        data.list.forEach(item => {
          let parentRegionName = ''
          let info = {
            continueFee: '',
            continueWeight: '',
            firstFee: '',
            firstWeight: '',
            parentRegionName: '',
            regionKey: item.code,
            regionName: item.name,
            bDelete: 0
          }
          if (item.code2) {
            info.code2 = item.code2
            info.regionName2 = item.name2
            parentRegionName = item.name2
          }
          if (item.code3) {
            info.code3 = item.code3
            info.regionName3 = item.name3
            parentRegionName = item.name3 + '-' + parentRegionName
          }
          if (item.code4) {
            info.code4 = item.code4
            info.regionName4 = item.name4
            parentRegionName = item.name4 + '-' + parentRegionName
          }
          info.parentRegionName = parentRegionName

          if (codeArr.indexOf(info.regionKey) === -1) {
            this.modelDialog.tableList.push(info)
          }
        })
      }
    },
    dealListStr (key, type) {
      return ExportStr(key, type)
    },
    handleSetRowClassName (row) {
      if (row.row.bDelete === 1) {
        return 'hide-row'
      } else {
        return ''
      }
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
